import { Context, Next } from "koa";
import jwt from 'jsonwebtoken';
import { reqHeaderKey, jwtConf } from '../config/index';
import { codeDefaultMsg, returnResult } from '../utils/response/returnResult';
export default class Middleware {
    /**
     * token校验
     * @param openUrl 忽略校验的url
     */
    public static verifyToken(openUrl: Array<string>) {
        return async (ctx: any, next: Next) => {
            const path = ctx.request.path;
            if (openUrl.includes(path)) return await next();
            try {
                const token = ctx.request.header[reqHeaderKey.USER_TOKEN];
                const user = jwt.verify(token, jwtConf.SECRET);
                ctx.user = user;
                await next();
            } catch (error) {
                ctx.status = 401;
                ctx.body = returnResult.error(codeDefaultMsg[401], 401);
            }
        };
    }
    /**
     * 错误中间件
     * @param ctx 
     * @param next 
     */
    public static async errorHandler(ctx: Context, next: Next) {
        try {
            await next();
        } catch (err) {
            console.log(err);
            let body = returnResult.error(err.message || codeDefaultMsg[500], 500);
            if (err !== undefined && err.status) { //处理抛出的已知错误
                body = err;
            }
            ctx.status = body.status;
            ctx.body = body;
        }
    }
}